const { ccclass, property } = cc._decorator;


const hide = false;
const show = true;


function debugToText(mjId) {
    let n = '';
    let x = mjId % 9 + 1;
    if (mjId < 9) {
        n = '筒';
    }
    else if (mjId < 18) {
        n = '条';
    }
    else {
        n = '万';
    }
    return x + n;
}

interface opt {
    node: cc.Node;
    sprite: cc.Sprite;
}

@ccclass
export default class MJGame extends cc.Component {

    /**game节点 */
    @property({
        type: cc.Node
    })
    gameRoot: cc.Node = null;

    @property({
        type: cc.Node
    })
    prepareRoot: cc.Node = null;


    @property({
        type: cc.Label,
        displayName: '自动托管的文字节点'
    })
    automaticText: cc.Label = null;


    /**剩余多少张牌的文字节点 */
    mjCount: cc.Label = null;

    /**剩余多少局的文字节点 */
    gameCount: cc.Label = null;

    /** 出牌的牌的复用节点*/
    @property({
        type: cc.Node,
        displayName: '出牌的牌的复用节点'
    })
    chuPaiDrag: cc.Node = null;

    /**自己手牌的Sprite数组 */
    myMJArr: cc.Sprite[] = [];

    /**四个玩家当前胡哪张牌的提示的容器 */
    huPaiTips: cc.Node[] = [];

    /**四个玩家胡牌后展示所有牌的容器 */
    huPaiLists: cc.Node[] = [];

    /**四个玩家所有碰、杠、等动画的数组 */
    playEfxs: cc.Animation[] = [];

    /**四个玩家当前出牌的sprite的数组 */
    chuPaiSprites: cc.Sprite[] = [];

    opts: opt[] = [];

    /**碰、杠等选择的容器 */
    options: cc.Node = null;



    /**被点击的麻将的node节点 */
    selectedMJ: cc.Node = null;
    onLoad() {
        if (!cc.sys.isNative && cc.sys.isMobile) {
            let cvs = this.getComponent(cc.Canvas);
            cvs.fitHeight = true;
            cvs.fitWidth = true;
        }

        if (!cc.vv) {
            console.log('MJGame.ts->onLoad-> cc.vv没有值', cc.vv.logStyle);
            cc.director.loadScene('loading');
            return;
        }




        cc.vv.animationNames = {
            PLAY_PENG: 'play_peng',
            PLAY_GANG: 'play_gang',
            PLAY_HU: 'play_hu',
            PLAY_ZIMO: 'play_zimo',
            PLAY_GUAFENG: 'play_guafeng',
            PLAY_XIAYU: 'play_xiayu',
        };


        this.addComponent('NoticeTip');
        this.addComponent('GameOver');
        this.addComponent('DingQue');
        this.addComponent('PengGangs');
        this.addComponent('MJRoom');
        this.addComponent('TimePointer');
        this.addComponent('GameResult');
        this.addComponent('Folds');
        this.addComponent('PopupMgr');

        this.addComponent('Voice');
        this.addComponent('UserInfoShow');
        this.addComponent('Status');

        this.initView();
        this.initAutomatic();
        this.initEventHandlers();
        this.addComponent('HuanSanZhang');

        this.gameRoot.active = false;
        this.prepareRoot.active = true;

        this.initWanFaLabel();
        this.onGameBegin();
        cc.vv.audioMgr.playBGM('bgFight.mp3');
        cc.vv.utils.addEscEvent(this.node);
    }


    /**初始化顶部玩法的说明文字 */
    initWanFaLabel() {
        const wanFaNode = cc.find('Canvas/infobar/wanfa').getComponent(cc.Label);
        wanFaNode.string = cc.vv.gameNetMgr.getWanfa();
    }


    /**碰、杠、胡、过的点击事件 */
    onOptionClicked(event: cc.Event.EventMouse) {
        switch (event.target.name) {
            case 'btnPeng':
                cc.vv.net.send(cc.vv.game_event_map.PENG);
                break;
            case 'btnGang':
                cc.vv.net.send(cc.vv.game_event_map.GANG, event.target.pai);
                break;
            case 'btnHu':
                cc.vv.net.send(cc.vv.game_event_map.HU);
                break;
            case 'btnGuo':
                cc.vv.net.send(cc.vv.game_event_map.GUO);
                break;
        }
    }


    /**每张手牌的点击事件 */
    onMJClicked(event: cc.Event.EventMouse) {
        if (cc.vv.gameNetMgr.isHuanSanZhang) {
            this.node.emit(cc.vv.game_event_map.MJ_CLICKED, event.target);
            return;
        }

        if (cc.vv.gameNetMgr.turn != cc.vv.gameNetMgr.seatIndex) {
            return;
        }

        for (let i = 0, l = this.myMJArr.length; i < l; i++) {
            if (event.target == this.myMJArr[i].node) {
                // 如果再次点击就是出牌
                if (event.target == this.selectedMJ) {
                    this.shoot(this.selectedMJ.mjId);
                    this.selectedMJ.y = 0;
                    return;
                }
                // 如果点击的是其他的牌则将上一次点击的牌放下去
                if (this.selectedMJ != null) {
                    this.selectedMJ.y = 0;
                }
                event.target.y = 15;
                this.selectedMJ = event.target;
                return;
            }
        }
    }


    start() {
        this.checkIp();
    }

    /**初始化视图 */
    initView() {
        // 初始化剩余多少张牌
        this.mjCount = this.gameRoot.getChildByName('mjcount').getComponent(cc.Label);
        this.mjCount.string = `剩余${cc.vv.gameNetMgr.numOfMJ}张`;

        // 初始化剩余多少局
        this.gameCount = this.gameRoot.getChildByName('gamecount').getComponent(cc.Label);
        this.gameCount.string = `${cc.vv.gameNetMgr.numOfGames}/${cc.vv.gameNetMgr.maxNumOfGames}局`;

        this.chuPaiDrag = this.gameRoot.getChildByName('chupaidrag');
        this.chuPaiDrag.active = false;

        // 给自己的手牌添加点击事件
        const myselfChild = this.gameRoot.getChildByName('myself');
        const myHolds = myselfChild.getChildByName('holds');
        myHolds.children.forEach((node) => {
            let sprite = node.getComponent(cc.Sprite);
            this.myMJArr.push(sprite);
            sprite.spriteFrame = null;
            this.initDragStuffs(sprite.node);
        });

        const realWidth = cc.director.getVisibleSize().width;
        myHolds.scaleX *= realWidth / 1280;
        myHolds.scaleY *= realWidth / 1280;

        // 把所有后面需要用到的东西存到this的对象里
        for (let key in cc.vv.directions) {
            const side = cc.vv.directions[key];
            const sideChild = this.gameRoot.getChildByName(side);

            this.huPaiTips.push(sideChild.getChildByName('HuPai'));
            this.huPaiLists.push(sideChild.getChildByName('hupailist'));
            this.playEfxs.push(sideChild.getChildByName('play_efx').getComponent(cc.Animation));
            this.chuPaiSprites.push(sideChild.getChildByName('ChuPai').children[0].getComponent(cc.Sprite));

            const opt = sideChild.getChildByName('opt');
            opt.active = false;
            const sprite = opt.getChildByName('pai').getComponent(cc.Sprite);
            const data: opt = {
                node: opt,
                sprite: sprite,
            };
            this.opts.push(data);
        }
        const opts = this.gameRoot.getChildByName('ops');
        this.options = opts;

        this.hideOptions();
        this.hideChuPai();
    }

    /**给手牌的每张牌添加点击拖拽事件 */
    initDragStuffs(node: cc.Node) {

        node.on(cc.Node.EventType.TOUCH_START, (event: cc.Event.EventMouse) => {
            // 如果不是自己的回合就退出
            if (cc.vv.gameNetMgr.turn != cc.vv.gameNetMgr.seatIndex) {
                return;
            }
            node.interactable = node.getComponent(cc.Button).interactable;
            if (!node.interactable) {
                return;
            }

            node.opacity = 255;
            this.chuPaiDrag.active = false;
            this.chuPaiDrag.getComponent(cc.Sprite).spriteFrame = node.getComponent(cc.Sprite).spriteFrame;
            this.chuPaiDrag.x = event.getLocationX() - cc.director.getVisibleSize().width / 2;
            this.chuPaiDrag.y = event.getLocationY() - cc.director.getVisibleSize().height / 2;
        });

        node.on(cc.Node.EventType.TOUCH_MOVE, (event: cc.Event.EventMouse) => {
            if (cc.vv.gameNetMgr.turn != cc.vv.gameNetMgr.seatIndex) {
                return;
            }
            if (!node.interactable) {
                return;
            }
            if (Math.abs(event.getDeltaX()) + Math.abs(event.getDeltaY()) < 0.5) {
                return;
            }

            node.opacity = 150;
            node.y = 0;
            this.chuPaiDrag.active = true;
            this.chuPaiDrag.opacity = 255;
            this.chuPaiDrag.scaleX = 1;
            this.chuPaiDrag.scaleY = 1;
            this.chuPaiDrag.x = event.getLocationX() - cc.director.getVisibleSize().width / 2;
            this.chuPaiDrag.y = event.getLocationY() - cc.director.getVisibleSize().height / 2;
        });

        node.on(cc.Node.EventType.TOUCH_END, (event: cc.Event.EventMouse) => {
            if (cc.vv.gameNetMgr.turn != cc.vv.gameNetMgr.seatIndex) {
                return;
            }
            if (!node.interactable) {
                return;
            }

            this.chuPaiDrag.active = false;
            node.opacity = 255;
            if (event.getLocationY() >= 200) {
                this.shoot(node.mjId);
            }
        });

        node.on(cc.Node.EventType.TOUCH_CANCEL, (event: cc.Event.EventMouse) => {
            if (cc.vv.gameNetMgr.turn != cc.vv.gameNetMgr.seatIndex) {
                return;
            }
            if (!node.interactable) {
                return;
            }

            this.chuPaiDrag.active = false;
            node.opacity = 255;
            if (event.getLocationY() >= 200) {
                this.shoot(node.mjId);
            }
        });
    }


    /**发送出牌消息 */
    shoot(mjId) {
        if (mjId == null) {
            return;
        }
        console.log('出的牌是：' + debugToText(mjId));
        cc.vv.net.send(cc.vv.game_event_map.CHUPAI, mjId);
    }

    /**隐藏碰、杠、胡父容器内的所有节点*/
    hideOptions() {
        this.options.active = false;
        this.options.children.forEach((child) => {
            if (child.name == 'op') {
                child.active = false;
                child.getChildByName('btnPeng').active = false;
                child.getChildByName('btnGang').active = false;
                child.getChildByName('btnHu').active = false;
            }
        });
    }


    /**隐藏四个玩家当前出牌的节点 */
    hideChuPai() {
        this.chuPaiSprites.forEach((sprite) => {
            sprite.node.active = false;
        });
    }

    /**检查玩家个数>=2有没有在同一个IP,并给出提示 */
    checkIp() {
        if (cc.vv.gameNetMgr.gamestate == '') {
            return;
        }

        const selfData = cc.vv.gameNetMgr.getSelfData();
        let ipMap = {};
        cc.vv.gameNetMgr.seats.forEach((seatData) => {
            if (seatData.ip != null && seatData.userId > 0 && seatData != selfData) {
                if (ipMap[seatData.ip]) {
                    ipMap[seatData.ip].push(seatData.name);
                }
                else {
                    ipMap[seatData.ip] = [seatData.name];
                }
            }
        });

        for (let k in ipMap) {
            let d = ipMap[k];
            if (d.length >= 2) {
                let str = d.join('\n') + '\n\n正在使用同一地址进行游戏！';
                cc.vv.alert.show('注意', str);
                return;
            }
        }
    }

    /**初始化各种监听事件 */
    initEventHandlers() {
        cc.vv.gameNetMgr.dataEventHandler = this.node;

        this.node.on(cc.vv.game_event_map.GAME_HOLDS, () => {
            this.initMahjongs();
            this.checkQueYiMen();
        });

        this.node.on(cc.vv.game_event_map.GAME_BEGIN, () => {
            this.initAutomatic();
            this.onGameBegin();
            // 第一把开局，要提示一下是否有>=2的玩家在同一IP
            if (cc.vv.gameNetMgr.numOfGames == 1) {
                this.checkIp();
            }
        });

        this.node.on(cc.vv.game_event_map.CHECK_IP, () => {
            this.checkIp();
        });

        this.node.on(cc.vv.game_event_map.GAME_SYNC, () => {
            this.onGameBegin();
            this.checkIp();
        });

        this.node.on(cc.vv.game_event_map.GAME_CHUPAI, (data) => {
            const data1 = data.detail;
            this.hideChuPai();
            this.checkQueYiMen();
            if (data1.last != cc.vv.gameNetMgr.seatIndex) {
                this.initMoPai(data1.last, null);
                
            }
            if (cc.vv.replayMgr.isReplay() == false && data1.turn != cc.vv.gameNetMgr.seatIndex) {
                this.initMoPai(data1.turn, -1);
            }
        });

        this.node.on(cc.vv.game_event_map.GAME_MOPAI, (data) => {
            this.hideChuPai();
            const data1 = data.detail;
            const pai = data1.pai;
            const localIndex = cc.vv.gameNetMgr.getLocalIndex(data1.seatIndex);
            if (localIndex == 0) {
                const index = 13;
                const sprite = this.myMJArr[index];
                this.setSpriteFrameByMJID(cc.vv.preAtlasString.M, sprite, pai);
                sprite.node.mjId = pai;
            }
            else if (cc.vv.replayMgr.isReplay()) {
                this.initMoPai(data1.seatIndex, pai);
            }
        });

        this.node.on(cc.vv.game_event_map.GAME_ACTION, (data) => {
            this.showAction(data.detail);
        });

        this.node.on(cc.vv.game_event_map.HUPAI, (data) => {
            const data1 = data.detail;
            // 如果不是玩家自己，则将玩家的牌都放到
            const seatIndex = data1.seatIndex;
            const localIndex = cc.vv.gameNetMgr.getLocalIndex(seatIndex);
            const huPai = this.huPaiTips[localIndex];

            huPai.active = true;

            if (localIndex == 0) {
                this.hideOptions();
            }

            const seatData = cc.vv.gameNetMgr.seats[seatIndex];
            seatData.hued = true;

            if (cc.vv.gameNetMgr.conf && cc.vv.gameNetMgr.conf.type == 'xlch') {
                huPai.getChildByName('sprHu').active = true;
                huPai.getChildByName('sprZimo').active = false;
                this.initHuPai(localIndex, data1.huPai);
                if (data1.isZiMo) {
                    if (seatData.seatIndex == cc.vv.gameNetMgr.seatIndex) {
                        (seatData.holds as number[]).pop();
                        this.initMahjongs();
                    }
                    else {
                        this.initOtherMahjongs(seatData);
                    }
                }
            }
            else {
                huPai.getChildByName('sprHu').active = !data1.isZiMo;
                huPai.getChildByName('sprZimo').active = data1.isZiMo;
                if (!data1.isZiMo && localIndex != 0) {
                    this.initMoPai(seatIndex, data1.huPai);
                }
            }

            if (cc.vv.replayMgr.isReplay() == true && cc.vv.gameNetMgr.conf && cc.vv.gameNetMgr.conf.type == 'xlch') {
                const opt = this.opts[localIndex];
                opt.node.active = true;
                opt.sprite.spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(cc.vv.preAtlasString.M, data1.huPai);
            }

            if (data1.isZiMo) {
                this.playEfx(localIndex, cc.vv.animationNames.PLAY_ZIMO);
            }
            else {
                this.playEfx(localIndex, cc.vv.animationNames.PLAY_HU);
            }

            cc.vv.audioMgr.playSFX('nv/hu.mp3');
        });

        this.node.on(cc.vv.game_event_map.MJ_COUNT, () => {
            this.mjCount.string = `剩余${cc.vv.gameNetMgr.numOfMJ}张`;
        });

        this.node.on(cc.vv.game_event_map.GAME_NUM, () => {
            this.gameCount.string = `${cc.vv.gameNetMgr.numOfGames}/${cc.vv.gameNetMgr.maxNumOfGames}局`;
        });

        this.node.on(cc.vv.game_event_map.GAME_OVER, () => {
            this.gameRoot.active = false;
            this.prepareRoot.active = true;
            cc.vv.gameNetMgr.isDingQueFinished = false;
            cc.vv.gameNetMgr.isAutomatic = false;
        });

        this.node.on(cc.vv.game_event_map.GAME_CHUPAI_NOTIFY, (data) => {
            this.hideChuPai();
            const seatData = data.detail.seatData;
            // 如果是自己则刷新手牌，否则刷新其他3个方位的牌
            if (seatData.seatIndex == cc.vv.gameNetMgr.seatIndex) {
                this.initMahjongs();
            }
            else {
                this.initOtherMahjongs(seatData);
            }
            this.showChuPai();
            // 播放音效
            const audioUrl = cc.vv.mahjongmgr.getAudioURLByMJID(data.detail.pai);
            cc.vv.audioMgr.playSFX(audioUrl);
        });

        this.node.on(cc.vv.game_event_map.GUO_NOTIFY, (data) => {
            this.hideChuPai();
            this.hideOptions();
            const seatData = data.detail;
            if (seatData.seatIndex == cc.vv.gameNetMgr.seatIndex) {
                this.initMahjongs();
            }
            cc.vv.audioMgr.playSFX('give.mp3');
        });

        this.node.on(cc.vv.game_event_map.GUO_RESULT, () => {
            this.hideOptions();
        });

        this.node.on(cc.vv.game_event_map.GAME_DINGQUE_FINISH, () => {
            this.initMahjongs();
            cc.vv.gameNetMgr.isDingQueFinished = true;
            this.automaticText.node.parent.active = true;

        });

        this.node.on(cc.vv.game_event_map.PENG_NOTIFY, (data) => {
            this.hideChuPai();

            const seatData = data.detail;
            if (seatData.seatIndex == cc.vv.gameNetMgr.seatIndex) {
                this.initMahjongs();
            }
            else {
                this.initOtherMahjongs(seatData);
            }

            const localIndex = cc.vv.gameNetMgr.getLocalIndex(seatData.seatIndex);
            this.playEfx(localIndex, cc.vv.animationNames.PLAY_PENG);
            cc.vv.audioMgr.playSFX('nv/peng.mp3');
            this.hideOptions();
        });

        this.node.on(cc.vv.game_event_map.GANG_NOTIFY, (data) => {
            this.hideChuPai();
            const data1 = data.detail;
            const seatData = data1.seatData;
            const gangType = data1.gangType;
            if (seatData.seatIndex == cc.vv.gameNetMgr.seatIndex) {
                this.initMahjongs();
            }
            else {
                this.initOtherMahjongs(seatData);
            }

            const localIndex = cc.vv.gameNetMgr.getLocalIndex(seatData.seatIndex);
            if (gangType == 'wangang') {
                this.playEfx(localIndex, cc.vv.animationNames.PLAY_GUAFENG);
                cc.vv.audioMgr.playSFX('guafeng.mp3');
            }
            else {
                this.playEfx(localIndex, cc.vv.animationNames.PLAY_XIAYU);
                cc.vv.audioMgr.playSFX('rain.mp3');
            }
        });

        this.node.on(cc.vv.game_event_map.HANGANG_NOTIFY, (data) => {
            const localIndex = cc.vv.gameNetMgr.getLocalIndex(data.detail);
            this.playEfx(localIndex, cc.vv.animationNames.PLAY_GANG);
            cc.vv.audioMgr.playSFX('nv/gang.mp3');
            this.hideOptions();
        });

        this.node.on(cc.vv.game_event_map.LOGIN_RESULT, () => {
            this.gameRoot.active = false;
            this.prepareRoot.active = true;
        });



    }

    /**
     * 播放动画
     * @param index 
     * @param name 
     */
    playEfx(index: number, name: cc.animationNames[keyof cc.animationNames]) {
        this.playEfxs[index].node.active = true;
        this.playEfxs[index].play(name);
    }


    /**开始游戏初始化各种信息 */
    onGameBegin() {
        // 隐藏所有动画节点
        this.playEfxs.forEach((animation) => {
            animation.node.active = false;
        });

        // 隐藏所有胡牌的节点
        this.huPaiLists.forEach((node) => {
            node.children.forEach((childNode) => {
                childNode.active = false;
            });
        });

        // 检查是不是拿到手牌直接就胡了的情况，然后初始化
        cc.vv.gameNetMgr.seats.forEach((seatData, i) => {
            let localIndex = cc.vv.gameNetMgr.getLocalIndex(i);
            let huPai = this.huPaiTips[localIndex];
            huPai.active = seatData.hued;
            if (seatData.hued) {
                huPai.getChildByName('sprHu').active = !seatData.isZiMo;
                huPai.getChildByName('sprZimo').active = seatData.isZiMo;
            }

            if (seatData.huInfo) {
                seatData.huInfo.forEach((info) => {
                    if (info.isHuPai) {
                        this.initHuPai(localIndex, info.pai);
                    }
                });
            }
        });

        this.hideChuPai();
        this.hideOptions();

        // 初始化除自己其他玩家的手牌(背面)
        for (let key in cc.vv.directions) {
            if (cc.vv.directions[key] == cc.vv.directions.myself) {
                continue;
            }
            let index = 0;
            switch (cc.vv.directions[key]) {
                case cc.vv.directions.right:
                    index = 1;
                    break;
                case cc.vv.directions.up:
                    index = 2;
                    break;
                case cc.vv.directions.left:
                    index = 3;
                    break;
            }
            const sideChild = this.gameRoot.getChildByName(cc.vv.directions[key]);
            const holds = sideChild.getChildByName('holds');
            holds.children.forEach((node, i) => {
                node.active = true;
                node.scaleX = 1.0;
                node.scaleY = 1.0;
                const sprite = node.getComponent(cc.Sprite);
                sprite.spriteFrame = cc.vv.mahjongmgr.holdsEmpty[index];
            });
        }


        if (cc.vv.gameNetMgr.gamestate == '' && cc.vv.replayMgr.isReplay() == false) {
            return;
        }

        this.gameRoot.active = true;
        this.prepareRoot.active = false;
        this.initMahjongs();

        cc.vv.gameNetMgr.seats.forEach((seatData, i) => {
            const localIndex = cc.vv.gameNetMgr.getLocalIndex(i);
            if (localIndex != 0) {
                this.initOtherMahjongs(seatData);
                if (i == cc.vv.gameNetMgr.turn) {
                    this.initMoPai(i, -1);
                }
                else {
                    this.initMoPai(i, null);
                }
            }
        });

        this.showChuPai();
        if (cc.vv.gameNetMgr.curAction != null) {
            this.showAction(cc.vv.gameNetMgr.curAction);
            cc.vv.gameNetMgr.curAction = null;
        }

        this.checkQueYiMen();
    }


    /**显示碰杠等信息的选项 */
    showAction(data: cc.curAction) {
        if (this.options.active) {
            this.hideOptions();
        }

        if (data && (data.hu || data.gang || data.peng)) {
            this.options.active = show;
            if (data.hu) {
                this.addOption('btnHu', data.pai);
                if (cc.vv.gameNetMgr.isAutomatic) {
                    cc.vv.net.send(cc.vv.game_event_map.HU);
                }
            }
            if (data.peng) {
                this.addOption('btnPeng', data.pai);
                if (cc.vv.gameNetMgr.isAutomatic) {
                    cc.vv.net.send(cc.vv.game_event_map.PENG);
                }
                
            }
            if (data.gang) {
                data.gangPai.forEach((gangPai) => {
                    this.addOption('btnGang', gangPai);
                });
                if (cc.vv.gameNetMgr.isAutomatic) {
                    cc.vv.net.send(cc.vv.game_event_map.GANG, data.gangPai[0]);
                }
            }
            
        }
    }

    /**更新碰杠等信息的选项 */
    addOption(btnName: string, pai: number) {
        for (let i = 0, l = this.options.children.length; i < l; i++) {
            let child = this.options.children[i];
            if (child.name == 'op' && child.active == false) {
                child.active = true;

                const sprite = child.getChildByName('opTarget').getComponent(cc.Sprite);
                sprite.spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(cc.vv.preAtlasString.M, pai);

                const btn = child.getChildByName(btnName);
                btn.active = true;
                btn.pai = pai;
                return;
            }
        }
    }

    /**根据当前回合显示哪个玩家的出的牌 */
    showChuPai() {
        const pai = cc.vv.gameNetMgr.chuPai;
        if (pai >= 0) {
            const localIndex = cc.vv.gameNetMgr.getLocalIndex(cc.vv.gameNetMgr.turn);
            const sprite = this.chuPaiSprites[localIndex];
            sprite.spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(cc.vv.preAtlasString.M, pai);
            sprite.node.active = true;
        }
    }



    /**
     * 初始化四个玩家摸牌位置的那个牌的UI
     * @param seatIndex 
     * @param pai 
     */
    initMoPai(seatIndex: number, pai: number) {
        const localIndex = cc.vv.gameNetMgr.getLocalIndex(seatIndex);
        const side = cc.vv.mahjongmgr.getSide(localIndex);
        const pre = cc.vv.mahjongmgr.getFoldPre(localIndex);
        const sideChild = this.gameRoot.getChildByName(side);
        const holds = sideChild.getChildByName('holds');
        const lastIdx = this.getMJIndex(side, 13);
        const moPaiNode = holds.children[lastIdx];

        moPaiNode.scaleX = 1.0;
        moPaiNode.scaleY = 1.0;

        if (pai == null) {
            moPaiNode.active = false;
        }
        else if (pai >= 0) {
            moPaiNode.active = true;
            if (side == cc.vv.directions.up) {
                moPaiNode.scaleX = 0.73;
                moPaiNode.scaleY = 0.73;
            }
            const sprite = moPaiNode.getComponent(cc.Sprite);
            sprite.spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(pre, pai);
        }
        else if (pai != null) {
            moPaiNode.active = true;
            if (side == cc.vv.directions.up) {
                moPaiNode.scaleX = 0.73;
                moPaiNode.scaleY = 0.73;
            }
            const sprite = moPaiNode.getComponent(cc.Sprite);
            sprite.spriteFrame = cc.vv.mahjongmgr.getHoldsEmptySpriteFrame(side);
        }
    }

    /**
     * 初始化除自己其他玩家的正面牌的信息(就是那些 杠、碰等牌，需要明出来的牌)
     * @param seatData 
     */
    initOtherMahjongs(seatData: cc.seat) {
        const localIndex = cc.vv.gameNetMgr.getLocalIndex(seatData.seatIndex);
        if (localIndex == 0) {
            return;
        }

        const side = cc.vv.mahjongmgr.getSide(localIndex);
        const sideRoot = this.gameRoot.getChildByName(side);
        const sideHolds = sideRoot.getChildByName('holds');
        const num = 3 * (seatData.pengs.length + seatData.anGangs.length + seatData.dianGangs.length + seatData.wanGangs.length);
        for (let i = 0; i < num; i++) {
            let idx = this.getMJIndex(side, i);
            sideHolds.children[idx].active = false;
        }

        const pre = cc.vv.mahjongmgr.getFoldPre(localIndex);
        const holds = this.sortHolds(seatData);
        if (holds != null && holds.length > 0) {
            for (let i = 0; i < holds.length; i++) {
                const idx = this.getMJIndex(side, i + num);
                const sprite = sideHolds.children[idx].getComponent(cc.Sprite);
                if (side == cc.vv.directions.up) {
                    sprite.node.scaleX = 0.73;
                    sprite.node.scaleY = 0.73;
                }
                sprite.node.active = true;
                sprite.spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(pre, holds[i]);
            }

            if (holds.length + num == 13) {
                const lastIdx = this.getMJIndex(side, 13);
                sideHolds.children[lastIdx].active = false;
            }
        }
    }


    /**
     * 获取牌在各座位上相对应的索引
     */
    getMJIndex(side, index) {
        if (side == cc.vv.directions.right || side == cc.vv.directions.up) {
            return 13 - index;
        }
        return index;
    }

    /**
     * 初始化胡的牌的展示的信息
     * @param localIndex 座位编码
     * @param pai 牌的编码
     */
    initHuPai(localIndex: number, pai: number) {
        if (cc.vv.gameNetMgr.conf && cc.vv.gameNetMgr.conf.type == 'xlch') {
            const huPaiList = this.huPaiLists[localIndex];
            for (let i = 0, l = huPaiList.children.length; i < l; i++) {
                let huPaiNode = huPaiList.children[i];
                if (huPaiNode.active == false) {
                    let pre = cc.vv.mahjongmgr.getFoldPre(localIndex);
                    huPaiNode.getComponent(cc.Sprite).spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(pre, pai);
                    huPaiNode.active = true;
                    break;
                }
            }
        }
    }


    /**如果玩家手上还有缺的牌没有打，则只能打缺牌 */
    checkQueYiMen() {
        if (cc.vv.gameNetMgr.conf == null || cc.vv.gameNetMgr.conf.type != 'xlch' || !cc.vv.gameNetMgr.getSelfData().hued) {
            // 遍历检查看是否有未打缺的牌， 如果有则需要将不是定缺的牌设置为不可用
            const dingQue = cc.vv.gameNetMgr.dingQue;
            let hasQue = false;
            if (cc.vv.gameNetMgr.seatIndex == cc.vv.gameNetMgr.turn) {
                for (let i = 0, l = this.myMJArr.length; i < l; i++) {
                    const sprite = this.myMJArr[i];
                    if (sprite.node.mjId != null) {
                        const type = cc.vv.mahjongmgr.getMahjongType(sprite.node.mjId);
                        if (type == dingQue) {
                            hasQue = true;
                            break;
                        }
                    }
                }
            }

            for (let i = 0, l = this.myMJArr.length; i < l; i++) {
                const sprite = this.myMJArr[i];
                if (sprite.node.mjId != null) {
                    const type = cc.vv.mahjongmgr.getMahjongType(sprite.node.mjId);
                    if (hasQue && type != dingQue) {
                        sprite.node.getComponent(cc.Button).interactable = false;
                    }
                    else {
                        sprite.node.getComponent(cc.Button).interactable = true;
                    }
                }
            }
        }
        else {
            if (cc.vv.gameNetMgr.seatIndex == cc.vv.gameNetMgr.turn) {
                for (let i = 0; i < 14; i++) {
                    let sprite = this.myMJArr[i];
                    if (sprite.node.active) {
                        sprite.node.getComponent(cc.Button).interactable = i == 13;
                    }
                }
            }
            else {
                for (let i = 0; i < 14; i++) {
                    let sprite = this.myMJArr[i];
                    if (sprite.node.active) {
                        sprite.node.getComponent(cc.Button).interactable = true;
                    }
                }
            }
        }
    }


    /** 更新手牌(去掉碰、杠、等特殊的牌然后排序)*/
    initMahjongs() {
        const seats = cc.vv.gameNetMgr.seats;
        const seatData = seats[cc.vv.gameNetMgr.seatIndex];
        const holds = this.sortHolds(seatData);
        if (holds == null) {
            return;
        }

        const lackingNum = 3 * (seatData.pengs.length + seatData.anGangs.length + seatData.wanGangs.length + seatData.dianGangs.length);
        holds.forEach((mjId, i) => {
            let sprite = this.myMJArr[i + lackingNum];
            sprite.node.mjId = mjId;
            sprite.node.y = 0;
            this.setSpriteFrameByMJID(cc.vv.preAtlasString.M, sprite, mjId);
        });
        for (let i = 0; i < lackingNum; i++) {
            let sprite = this.myMJArr[i];
            sprite.node.mjId = null;
            sprite.spriteFrame = null;
            sprite.node.active = false;
        }
        for (let i = lackingNum + holds.length; i < this.myMJArr.length; i++) {
            let sprite = this.myMJArr[i];
            sprite.node.mjId = null;
            sprite.spriteFrame = null;
            sprite.node.active = false;
        }
    }


    /**
     * 把刚摸到的牌去掉，然后排序，定缺的排最右边，然后把刚摸的牌添加回去并返回排好序的牌
     * @param seatData 
     */
    sortHolds(seatData: cc.seat) {
        const holds = <number[]>seatData.holds;
        if (holds == null) {
            return;
        }

        // 如果手上牌的数目是2,5,8,11,14,表示最后一张牌是刚摸到的
        let moPai = null;
        const l = holds.length;
        if (l == 2 || l == 5 || l == 8 || l == 11 || l == 14) {
            moPai = holds.pop();
        }

        const dingQue = seatData.dingQue;
        cc.vv.mahjongmgr.sortMJ(holds, dingQue);

        // 将摸的牌添加回去
        if (moPai != null) {
            holds.push(moPai);
        }
        return holds;
    }


    /** 根据前缀麻将ID设置对应的图片，并把节点显示出来*/
    setSpriteFrameByMJID(pre: cc.preAtlasString[keyof cc.preAtlasString], sprite: cc.Sprite, mjId) {
        sprite.spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(pre, mjId);
        sprite.node.active = true;
    }


    onDestroy() {
        if (cc.vv) {
            cc.vv.gameNetMgr.clear();
        }
    }


    /**自动托管的点击事件 */
    onBtnAutomaticClicked() {
        cc.vv.gameNetMgr.isAutomatic = !cc.vv.gameNetMgr.isAutomatic;
        const str = cc.vv.gameNetMgr.isAutomatic ? '取消托管' : '自动托管';
        this.automaticText.string = str;
        if(cc.vv.gameNetMgr.isAutomatic){
            this.autoChuPai();
        }
    }

    initAutomatic() {
        this.automaticText.string = '自动托管';
        this.automaticText.node.parent.active = false;
    }

    /** 自动出牌*/
    autoChuPai() {
        
        if (cc.vv.gameNetMgr.turn != cc.vv.gameNetMgr.seatIndex) {
            return;
        }
        for (let i = this.myMJArr.length - 1, l = this.myMJArr.length; i >= 0; i--) {

            let node = this.myMJArr[i].node;
            if (!node.getComponent(cc.Button).interactable) {
                continue;
            }

            this.shoot(node.mjId);
            return;
        }
    }
    
}


